henrikjoreteg / happy.js Goto Github PK
View Code? Open in Web Editor NEW$('form').isHappy() – Lightweight, extensible form validation plugin for jQuery/Zepto.js
Home Page: http://projects.joreteg.com/Happy.js/
License: MIT License
$('form').isHappy() – Lightweight, extensible form validation plugin for jQuery/Zepto.js
Home Page: http://projects.joreteg.com/Happy.js/
License: MIT License
I was wondering, when validating an e-mail address I need to run multiple tests, and depending on the outcome the error message differs.
For example:
$('#form').isHappy({
fields: {
'#email': {
required: true,
test: function(val) {
if (/^(?:\w+\.?\+?)*\w+@(?:\w+\.)+\w+$/.test(val)) {
$.post('/check-email', { email: val }, function(available) {
// message = E-mail address already taken!
return available;
});
} else {
// message = Not a valid e-mail address!
return false;
}
},
message: '*See test function*'
}
}
});
Is this posible? If yes, how?
Thanks!
I could really use an onUnhappy callback. There is some js I'd like to run when the form is not happy. It will talk to the user and make sure they know about it. This is for a broad message that would be more attention-getting than the field specifics. I would like this to be invoked only onSubmit. That makes it even more forgiving than the empty blur (issue #4). We don't want to state being unhappy unless the user insists to proceed with invalid data.
If a field is required but empty and has already been earmarked as unhappy, it seems strange to then remove the error message on blur if the field if its still empty.
This :
if (required === true && val.length === 0) {
..seems to operate better than:
if (submit === true && required === true && val.length === 0) {
Curious what others thought...
The unhappy state works perfectly on blur. Any thoughts on adding a happy state on blur, essentially, throwing a span with a class="happyMessage"?
Why not forwarding an event in arguments?
https://github.com/HenrikJoreteg/Happy.js/blob/master/happy.js#L39
I just want use in my custom code;
happy: function(event) {
event.preventDefault();
}
If you don't provide a message the field seems to skip validation.
I can use
or just use .unhappyMessage { display: none }
I actually just like the visual style change.
I am not sure if this is a bug or something I am doing wrong but Happy doesn't seem to work with partial selectors.
Syntax error, unrecognized expression: '[id$=casecreate-subject-input]'
I also tried using the class selector but even though it doesn't produce an error it ignores the validation
fields: {
'.subject': {
required: true,
message: 'hey'
}
Sometimes you don't want to put a span next to the form field, and just want to highlight the field, I've added on my fork of this library an option to fields called show_message, true by default, that you can set to false if you don't want it.
Hello,
I'm trying to do some tweaks to your little validation script, and I'm wondering what was the reason why you wrote this part of the code called "clean it or trim it":
// clean it or trim it
if (isFunction(opts.clean)) {
val = opts.clean(el.val());
} else if (!password && typeof opts.trim === 'undefined' || opts.trim) {
val = trim(el);
} else {
val = el.val();
}
// write it back to the field
el.val(val);
Documentation says:
arg (anything): ...or to make a server call to check if a username is available
However, from reading the source it looks like arg
function must be synchronous
error = !opts.test(val, arg);
which isn't going to work well for server calls.
Is this correct or is there a way to have arg
be async function?
The ability to add a message for the whole form, which could be positioned anywhere on the form (generally on top or bottom). E.G. 'Please fill in all fields'.
JS example:
$('#awesomeForm').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#yourName': {
required: true,
message: 'Might we inquire your name'
},
'#email': {
required: false,
message: 'How are we to reach you sans email??',
test: happy.email // this can be *any* function that returns true or false
}
}
formMessage: 'Please fill in all fields';
});
Add the ability to place the error message before or after the input. Sometimes it is nice that it floats next to the input, so maybe the error message can be placed inside a certain element.
i dont understand how to validate whether is a valid email address
There is no error handling, so if a test on an attribute throws an exception, the form gets submitted.
While the bug is clearly elsewhere (the test throwing the exception) this is really hard to debug because the page navigates before the exception can be seen.
To me, the onBlur validation is more of an issue than a feature. It makes sense when there is form data that is wrong (a custom test failing some input). But what if I immediately go back to correct a previous field and the current one is required -- it gets immediately unhappy. I haven't even started typing yet... It easily sets a negative vibe for every required field I touch. I think the minimal solution would be for required to trigger unhappy only onSubmit. This way we give people freedom to move around and click around at will, without warnings for no reason. So I can set a field.focus() without worrying it will look bad if it gets unfocused. Yes, I want people to know if they have typed something invalid, but I don't want to cause unhappy moods if they haven't even started typing yet. Less noise = more happy.
I'm happy to add anyone who will try their best to:
Sorry this has been sitting for too long, would like to add maintainers rather than have it slip into bad shape over time, since obviously many people are happily using it.
Let me know if you're interested and I'll add you.
Is there any "approved by author" minified version?
Does happy.js support control groups? It doesn't seem to work for me.
Here is a screenshot, it shows the error repeatedly for each checkbox, I expected just one error to show.
I found this:
https://github.com/StanAngeloff/Happy.js/blob/86bd64e2eab12f22e3cd0007c1a40e7eadfb00c4/happy.js
Hello,
Thanks for this little-baby script. I really like it, however I don't like the way it handles displaying error messages. When I trigger submit button on the form and get error messages they disappear when I click any field. Instead they should disappear when the fields become valid.
Is there any way to improve that? Can you propose a simple solution?
Thanks
Am facing a strange behavoir, when i try to select a prior entered text with in a check box, it turned out that the value is always resetted, not matter if it is neccessary or not.
to solve this - i will open a PR soon.
Is there any way to validate all fields on blur instead of exclusively on submit?
The below (three fields; at least one must be completed) works fine on submit, but stays unhappy on blur:
<form id="form">
<input id="field1" name="field1">
<input id="field2" name="field2">
<input id="field3" name="field3">
</form>
var field1 = false
var field2 = false
var field3 = false
$('#form').isHappy({
when: 'blur change submit',
fields: {
'#field1': {
'required': 'sometimes',
'test': function (val) {
field1 = (val) ? true : false
return (val || field2 || field3)
}
},
'#field2': {
'required': 'sometimes',
'test': function (val) {
field1 = (val) ? true : false
return (val || field1 || field3)
}
},
'#field3': {
'required': 'sometimes',
'test': function (val) {
field1 = (val) ? true : false
return (val || field1 || field2)
}
}
}
})
I'm currently in the situation that I need to wait for some asynchronous scripts to finish after form validation passes, before the form is actually sent. To this end, additionally accepting a promise for the happy callback would be very helpful.
It'll be great if the message displayed for a field could change based on the result of the test and if its required.
So for example if an email input is empty you'd display "field required", if its filled in but invalid display "valid email address required"... etc.
I would like to overwrite the way the error message is handled. I want to use the id of the field to select it and them use the placeholder attribute to show the error message.
How do I overwrite the default validation error?
This is what I have:
$('#generator').isHappy({
errorTemplate: function( el ) {
if(el && typeof(el) !== 'undefined') {
console.log( el );
}
},
fields: {
// but you could certainly do $('[name=name]') as well.
'#first-sleeper-first-name': {
required: true,
message: 'Might we inquire your name'
},
'#first-sleeper-last-name': {
required: true,
message: 'How are we to reach you sans email??',
test: happy.email // this can be *any* function that returns true or false
}
}
});
I keep getting these error on validation error:
Any help?
I'm currently setting up Happy.js in a Node/Babel environment. Would love to see an NPM package.
Also, this
is undefined in my setup in the browser; to easily add the isHappy
function to jQuery without altering the source code, a change from
(this.jQuery || this.Zepto)
to
(window.jQuery || window.Zepto)
or something similar would be helpful.
Probably just a way to pass in a function that gets the simple error object and returns HTML.
selector:[name=youName]
fix :
var error = {
message: opts.message || '',
id: (field.attr("id") ||field.attr("name")) + '_unhappy'
};
From issue #19
If a field has the required attribute set to false and you type something incorrect (invalid) in the input and try and submit the form it shows the error message, this is working fine. It is only when you then empty the input and and try and validate the form again the message will stay.
For example do this on the test from in the happy.js pack. Set the email required attribute to false and when you test leave the name field empty, then type an invalid email into the email input, submit the from, then remove the content from the email input and submit again.
The original issue ended up taking on a life of its own cause of a UI bug so I'm duplicating this here cause the original issue (don't clear validation errors on required elements simply cause the element was cleared and blurred) still stands IMO
If you want multiple tests on an input there should be a sensible way of doing that. Currently the two approaches are:
Happyjs.com documentation states
$('#awesomeForm').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
[...]
The attribute selector comment is certainly not true. Using the following as a selector for the name field (exactly as the demo is formatted) throws errors:
"[name='name']": {
required: true,
message: 'Might we inquire your name'
},
"[name=name]": {
required: true,
message: 'Might we inquire your name'
},
"name='name'": {
required: true,
message: 'Might we inquire your name'
},
"name=name": {
required: true,
message: 'Might we inquire your name'
},
Take your example fiele and:
Append Jon to "My name is" and click on document 2 times - counter encrease 4 times;
Append Smith to "My name is Jon" and click on document - conter encerease 6 times ??
Erase the field - counter encrease all the time.
If it not work, just type something in Input and:
focus and blur it,
focus and blur,
click on document,
focus and blur,
click on document...
the counter should increase as a crazy!
It look's like "function testValid(submit) {}" fires once in the begining, but after that event fires several time on the same element.
I tested it on FF and chrome in Linux and windows 7.
Why?
Someday
I'm attempting to use the unhappy method to call a custom function when the field requirements aren't met. I'm using the "when" method to check the fields on "blur." The unhappy method works great when I submit the form, but not on blur.
Focusing an error clears the other errors. I am not clear on what might cause this.
But the same thing happens in the demo provided with the package.
Could someone please explain how to use the equal function in Happy.js to compare 2 password fields?
I can't seem to get this to work.
Example here. http://codepen.io/anon/pen/zGdJjp
After submitting a valid input, any mouseup event with the text input in focus will cause the cursor to move to the end of the input. I found that testValid and handlMouseUp were being called on every mouseup in the window after the submission. I fixed this in my own project by changing the event bindings for those two functions from 'bind' to 'one.'
How can I prevent form submission on ajax call?
As soon as I make an ajax call to get some data from server, my form gets submitted. How to prevent this?
Code is as follows:
` unHappy: function (values) {
if ($('#home').find('span.unhappyMessage').length !== 0) {
$('.one').css('background-color', 'red');
} else {
$('.one').css('background-color', 'white');
}
if ($('#mother').find('span.unhappyMessage').length !== 0) {
$('.two').css('background-color', 'red');
} else {
$('.two').css('background-color', 'white');
}
if ($('#father').find('span.unhappyMessage').length !== 0) {
$('.three').css('background-color', 'red');
} else {
$('.three').css('background-color', 'white');
}
if ($('#officer').find('span.unhappyMessage').length !== 0) {
$('.four').css('background-color', 'red');
} else {
$('.four').css('background-color', 'white');
}
if ($('#informant').find('span.unhappyMessage').length !== 0) {
$('.five').css('background-color', 'red');
} else {
$('.five').css('background-color', 'white');
}
},
happy: function (values) {
$('.one').css('background-color', 'white');
$('.two').css('background-color', 'white');
$('.three').css('background-color', 'white');
$('.four').css('background-color', 'white');
$('.five').css('background-color', 'white');
},
`
I am testing the demo.html and the min max length is not working
test: [minLength, maxLength], arg: [3, 1]
I noticed that the two functions were called but the array [3, 1] is passed instead of a single value.
This issue ended up drifing into a new issue, for the original go here #34
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.