Javascript regex to detect emptiness or specific pattern - javascript

I'm using jQuery Validate for my form. I added an additional method to check for valid SSN values.
$.validator.addMethod(
'ssn',
function(e,i,a) {
return e.match(/^(\d{10})$/);
},
'SSN is not valid'
);
It works fine, but the problem is that the field is not required, and if the user does not input any data in the field, it still gets validated and throws an error.
This validation should only take place IF and ONLY IF the user actually inputs some data in that field. How can I cover that in the regex? Thanks!

Please try the following. By adding ? it now expects an optional 10 digits.
$.validator.addMethod(
'ssn',
function(e,i,a) {
return e.match(/^(\d{10})?$/);
},
'SSN is not valid'
);

Related

Debug jQuery form validation

I have a form that submits to a url using the action attribute <form action='/example/url'>. It uses the jQuery validation plugin.
jQuery("form#page-0").validate({
ignore: ':hidden'
,rules: {"product_id_page-0":{"required":true},"name_f":{"required":true,"regex":["^[^=:<>{}()\"]+$",""]},"name_l":{"required":true,"regex":["^[^=:<>{}()\"]+$",""]},"email":{"required":true,"remote":{"url":"\/premium\/ajax?do=check_uniq_email&_url=L3ByZW1pdW0vbG9naW4\/YW1lbWJlcl9yZWRpcmVjdF91cmw9JTJGcHJlbWl1bSUyRnNpZ251cC5waHA="}},"login":{"required":true,"rangelength":["6","32"],"regex":["^([0-9a-zA-Z_][0-9a-zA-Z_ ]+[0-9a-zA-Z_]|[0-9a-zA-Z_]+)$",""],"remote":{"url":"\/premium\/ajax?do=check_uniq_login"}},"pass":{"required":true,"rangelength":["6","32"]},"_pass":{"required":true}}
,messages: {"product_id_page-0":{"required":"Please choose a membership type"},"name_f":{"required":"Please enter your First Name","regex":"Please enter your First Name"},"name_l":{"required":"Please enter your Last Name","regex":"Please enter your Last Name"},"email":{"required":"Please enter valid Email","remote":"--wrong email--"},"login":{"required":"Please enter valid Username. It must contain at least 6 characters","rangelength":"Please enter valid Username. It must contain at least 6 characters","regex":"Username contains invalid characters - please use digits, letters or spaces","remote":"--wrong login--"},"pass":{"required":"Please enter Password","rangelength":"Password must contain at least 6 letters or digits"},"_pass":{"required":"This field is required"}}
//,debug : true
,errorPlacement: function(error, element) {
error.appendTo( element.parent());
}
,submitHandler: function(form, event){form.submit();}
// custom validate js code start
,errorElement: "span"
// custom validate js code end
});
The problem is that sometimes the form submits to the url before the validator fires. I'm suspicious of submitHandler: function(form, event){form.submit();} because I don't understand what the event parameter is doing. In the documentation for jquery validation there's no mention of a second parameter.
Any suggestions for debugging the form are also welcome. Variables to log or other ways to view what's happening. I did set debug:true but it doesn't seem to spit any errors to the console.
The problem is that sometimes the form submits to the url before the validator fires.
It might be because you've specified a non-existant rule. There is no such rule/method called regex. However, there is one called pattern contained within the additional-methods.js file. This is the root cause of your problems. Once the required rule is satisfied, the plugin attempts to evaluate the regex rule and chokes.
I'm suspicious of submitHandler: function(form, event){form.submit();} because I don't understand what the event parameter is doing. In the documentation for jquery validation there's no mention of a second parameter.
If you don't understand what it's doing and it's not in the docs, then why did you put the event argument into your code?
The documentation is correct, there is no second argument. However, having the additional arguments is merely superfluous and will not break anything.
You employ a very unusual code formatting style that makes it difficult to read and troubleshoot.
,submitHandler: function(form, event){form.submit();}
There is no second argument for this callback, so you can remove event.
Since you only have form.submit() within your submitHandler, it's not doing anything different from the default. In other words, remove the entire submitHandler, and after validation the form will submit to the action attribute as per the default.
NOTES:
ignore: ":hidden" is the default behavior, so you don't need to specify it.
It's not necessary to enclose the rule names within quotes.
DEMO: http://jsfiddle.net/1e82p64f/

how to make a regex string reject a blank field [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I am very new to coding so go easy.
I am trying to make a email validation form but it needs to reject a blank cell (input box) sorry for being so bad at coding..... i also was going to use a regex
it has to be alpanumeric#alpanumeric.alpanumeric
sorry
The correct behavior in this case would be to perform a "pre-check" on fields before actually executing some more complex validation (eg: regular expressions).
The logic would look something like this:
valid_email = false;
email = strip_leading_trailing_spaces( email ); // don't forget to cleanup user input
if ( email != "" ) {
// perform regex testing here, set valid_email to false if failed
}
// handle "valid_email" variable here
It's worth noting here that any client side validation should be duplicated to/re-checked on the server as any user with a little knowledge in JS could easily bypass any validation done on the clients computer.
You don't need a regex if you are just checking to see if it's empty:
<input type=text id=email><button onClick="validate()">Validate</button>
<script language="javascript">
function validate() {
if ($("#email").val().length == 0) {
alert("Enter an email address");
}
}
</script>
with a regexp :
var valid_email = ! email.match( /^\s*$/ ) ;
If there's only spaces and tabs or nothing then valid_email = false
demo : http://regex101.com/r/iX8lF7/1

Optional Field validation

I am having some problem in JavaScript form validation.
I have some optional fields in my HTML code. On submit, they don't need to be filled up but if the user provides some input they must be verified. For instance, I have an optional phone number field. If the user provides an input then I need to check if they are all numbers.
How could I do that?
You need only invoke the validation code if the field value meets some precondition, in this case: if the field has a value (checked by testing the length property of the string value):
var fieldValue = document.getElementById("someInput").value;
if( fieldValue.length > 0 ) {
if( someValidationFunction( fieldValue ) ) alert("Field is invalid");
}
What's stopping you from using HTML5's own validation?
<input type="tel" pattern="[0-9]+" />
No JavaScript required, will work on all modern browsers.
A note on security: Please don't rely on client-side validations for security concerns, as they can be trivially disabled. All validation should also be done server-side.
you can bind your custom method as a callback to your submit action in your form
<form onSubmit="return customValidation()>
In the method do your validations.
function customValidation()
{
//code to test fields
fieldToValidate = document.getElementById("field-id")
//validate the field
}
You can't use the other answers if you need it to be more secure; you shouldn't do this with JavaScript, because if a user for some reason has it turned off in their browser (or they turned it off on purpose) then the form won't still be verified. Instead you need to do it with PHP on the server. On the server that the form is being sent to you need to get the query strings sent with the form ($_GET['phonenumber'];), and see if it's a number (int intval ( mixed $phonenumber )). This should return NaN if it's not a number.

mootools form validator accept blank and email validation

I am trying to allow Blank inputs on my form but also validate an email if ever the user inputs one, i already changed the regex several times with the ones that i find here in stackoverflow that allows blank input but all of them doesn't work
here is the original code:
['validate-email', {
errorMsg: Form.Validator.getMsg.pass('email'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]\.?){0,63}[a-z0-9!#$%&'*+\/=?^_`{|}~-]#(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\])$/i).test(element.get('value'));
}
}],
how can i allow my mootools form validator to accept blanks but also verify email if there is any input?
Direct Source:
http://mootools.net/docs/more/Forms/Form.Validator
I see two options.
Option 1
Remove the required class from the input element. That will accept an empty value but check/validate if not empty. Try it here.
Option 2
The one you already have :)
I normally use this regex:
/^[a-z0-9._%-]+#[a-z0-9.-]+\.[a-z]{2,4}$/i
Found also this one. Anyway, it works; check this demo.
Email validation regex is so clumsy... Does mootools support validation functions?
Anyway, you can take your regex and create a bit more clumsy one: original-regex|^$, which will accept empty string

Is there anyway i can disable user to input a custom word or two in jquery validate plugin?

I'm using jquery validate plugin to validate my php form, now i'm stuck with validating for a custom word, what i want to do is, disable user to input two words, for example:
word1, word2.
Is there any simple way to do it, i tried with some custom methods, but i have no idea what am i doing. Is there anyone able to provide me one?
custom: {
required: true,
words: "word1,word2",
},
And in my controller
custom: function( value, element ) {
return this.optional(element) || /^-?(?:\word1,word2\)?$/.test(value);
},
You need to add a method for words (same as 'words:') to declare a custom function which jqvalidate will use. This should be added before you call jQuery.validate();
jQuery.validator.addMethod("words", function(value, element) {
return this.optional(element) || /^/(?!Hello)(?!World)$/.test(value);
}, "Only Hello and World are allowed");
See validator AddMethod for reference. No controller code is required.
Try to search for answers within stackoverflow.

Categories