jQuery Validation - password MUST contain uppercase and number - javascript

So in my registration form I have this field:
<div class="form-group">
<label for="RegisterModel_Password">Password</label>
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password" class="form-control"
required="required" minlength="8"/>
</div>
As you see, I'm using jQuery validation attributes to ensure that the password includes at least 8 characters. So, I want to check if password contains uppercase and number, if not, field is not valid. I downloaded additional method for jQuery Validation plugin named "pattern" and added her in head tag.
I tried to do this as follows but it didn't worked.
$("#formRegister").validate({
rules: {
RegisterModel_Password: {
pattern: /^[a-zA-Z][0-9]/
}
}
});
I assume that the pattern is wrong, but I'm not sure whether the use is correct.
Thank you for your help.

Chains of regular expressions are too hard for me ( I have never tried to learn them lol ). So here is my solution:
jQuery.validator.addMethod("passwordCheck",
function(value, element, param) {
if (this.optional(element)) {
return true;
} else if (!/[A-Z]/.test(value)) {
return false;
} else if (!/[a-z]/.test(value)) {
return false;
} else if (!/[0-9]/.test(value)) {
return false;
}
return true;
},
"error msg here");
And simply I use it like a attribute:
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password"
class="form-control"
required="required" minlength="8"
passwordCheck="passwordCheck"/>
Thanks for your answers.

You can add your custom validation using $.validator.addMethod() like:
$.validator.addMethod("validation_name", function(value) {
// at least 1 number and at least 1 character
[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
});

Related

indexOf is not a function error while focusing on an input

$('input').focusout(function() {
if ($(this).indexOf('#') > -1 && $(this).indexOf('.') > -1) {
$('.status').html('Valid Email');
} else {
$('.status').html('Your email is invalid, Please try again');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="email" placeholder="Email">
<p class="status"></p>
When I focus out from input area, it gives error indexOf is not a function.
There are two things you should consider in your solution.
$(this) will refer to its parent which is in your particular case it is $('input'). So if you want to check whether # or . exists in your input value, you should refer to val() method within your query, so it will return the current value of your input.
So your final code should be something like this:
$('input').focusout(function() {
if ($(this).val().indexOf('#') > -1 && $(this).val().indexOf('.') > -1) {
$('.status').html('Valid Email');
} else {
$('.status').html('Your email is invalid, Please try again');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="email" placeholder="Email">
<p class="status"></p>
Whilst your solution for checking special symbols in email working fine it won't check the entire input characters. So the best way (best practice) to check such a thing is to using regular expressions. Thus you should create a proper regex with either RegExp or regular expression literals.
So your final code would be like this:
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('input').focusout(function() {
if (emailRegex.test($(this).val())) {
$('.status').html('Valid Email');
} else {
$('.status').html('Your email is invalid, Please try again');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="email" placeholder="Email">
<p class="status"></p>

How to force validate data of the HTML 5 input from jquery?

I do have a input with the pattern and the title to show the error in case of wrong data, I do need to not use the post method, so I just make some Jquery code to use the input validation, but I can't find how to show the default message of the input
This is the HTML5 input:
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
And this is the jquery code:
$("#inputEnviar").click(
function(){
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if ( userValidation ){
//code to do whatever I have to do if the data is valid
} else {
//if the data is invalid
//the input already has a default message to show
//then, how do I force to show
$("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
}
});
If the validation fails, in your else code block, set the custom message that you want to notify to the user:
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
Then, you can use reportValidity() to show that message. From MDN:
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
$("#inputEnviar").click(
function() {
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if (userValidation) {
//code to do whatever I have to do if the data is valid
} else {
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
var isValid = $('#user')[0].reportValidity();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
<input id="inputEnviar" type="button" value="Send">
For old browsers (i.e. IE) you would need to use a polyfill.
There are several implementations around (like this git). This article goes deeper on the topic.
This should work. The reportValidity() function will show the default message after you have set it with setCustomValidity.
function send() {
var input = $("#user")[0];
input.setCustomValidity("");
if(!input.checkValidity()) {
input.setCustomValidity("watch me break");
input.reportValidity();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>

The form does not work correctly when sent

I wrote the code for a form validation.
Should work like this:
It checks (allLetter (uName)) and if it's true, then validate the next input.
If any validation is false then it should return false.
My problem is that if both validations are true, then everything is exactly false and the form is not sent.
If I set true in formValidation (), if at least one check false, the form should not be sent.
<form name='registration' method="POST" onSubmit="return formValidation();">
<label for="userName">Name:</label>
<input type="text" name="userName" size="20" />
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" size="20" />
<input type="submit" name="submit" value="Submit" />
</form>
function formValidation() {
var uName = document.registration.userName;
var uPhone = document.registration.userPhone;
if(allLetter(uName)) {
if(phone(uPhone)) {}
}
return false;
}
function phone(uPhone){
var digts = /^[0-9]+$/;
if(uPhone.value.match(digts)){
return true;
} else {
alert('Phone must have only digits');
uPhone.focus();
return false;
}
}
function allLetter(uName) {
var letters = /^[A-Za-z]+$/;
if(uName.value.match(letters)) {
return true;
}else{
alert('Username must have alphabet characters only');
uName.focus();
return false;
}
}
First, you are using a 20+ year old way to gain references to your elements (document.form.formElementNameAttributeValue) and, while this still works for legacy reasons, it doesn't follow the standard Document Object Model (DOM) API.
Next, you've broken up your validation tests into different methods (and that's certainly not a bad idea for reusability), but in this case is is adding a ton of code that you just don't need. I've always found it's best to start simple and get the code working, then refactor it.
You're also not using the <label> elements correctly.
One other point, your form is set to send its data via a POST request. POST should only be used when you are changing the state of the server (i.e. you are adding, editing or deleting some data on the server). If that's what your form does, you'r fine. But, if not, you should be using a GET request.
Lastly, you are also using a 20+ year old technique for setting up event handlers using inline HTML event attributes (onsubmit), which should no longer be used for many reasons. Additionally, when using this technique, you have to use return false from your validation function and then return in front of the validation function name in the attribute to cancel the event instead of just using event.preventDefault().
So, here is a modern, standards-based approach to your validation:
// Get references to the elements you'll be working with using the DOM API
var frm = document.querySelector("form[name='registration']");
var user = document.getElementById("userName");
var phone = document.getElementById("userPhone");
// Set up event handlers in JavaScript, not with HTML attributes
frm.addEventListener("submit", formValidation);
// Validation function will automatically be passed a reference
// the to event it's associated with (the submit event in this case).
// As you can see, the function is prepared to recieve that argument
// with the "event" parameter.
function formValidation(event) {
var letters = /^[A-Za-z]+$/;
var digts = /^[0-9]+$/;
// This will not only be used to show any errors, but we'll also use
// it to know if there were any errors.
var errorMessage = "";
// Validate the user name
if(user.value.match(letters)) {
// We've already validated the user name, so all we need to
// know now is if the phone is NOT valid. By prepending a !
// to the test, we reverse the logic and are now testing to
// see if the phone does NOT match the regular expression
if(!phone.value.match(digts)) {
// Invalid phone number
errorMessage = "Phone must have only digits";
phone.focus();
}
} else {
// Invalid user name
errorMessage = "Username must have alphabet characters only";
user.focus();
}
// If there is an error message, we've got a validation issue
if(errorMessage !== ""){
alert(errorMessage);
event.preventDefault(); // Stop the form submission
}
}
<!-- 20 is the default size for input elements, but if you do
want to change it do it via CSS, not HTML attributes -->
<form name='registration' method="POST">
<!-- The for attribute of a label must be equal to the id
attribute of some other element, not the name attribute -->
<label for="userName">Name:</label>
<input type="text" name="userName" id="userName">
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" id="userPhone">
<input type="submit" name="submit" value="Submit">
</form>

Regex for jquery password

I am busy using a jquery script that validates users password in real time. I would like to adjust it only accept a password if it has a letter, number and special character in it.
jQuery("#ValidEmail").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a valid Email ID"
});
jQuery("#ValidPassword").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a special character"
});
I am stumped on how to do this as it does not accept normaly regex experesions that I can find off the web eg
(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Any idea on how to solve this. Im bashing my head in here
As far as I can tell from the documentation, what you're using is not a supported syntax for adding validation methods to jQuery validate:
/* INCORRECT: */
jQuery("#element").validate({
expression: "if (/*...*/) return true; else return false;",
message: "Please enter a valid Email ID"
});
If you need custom validation rules, that is done with addMethod():
/* CORRECT: */
jQuery.validator.addMethod("methodname", function(value, element) {
// return true if value is valid
}, "message");
jQuery("#myform").validate({
rules: {
elementname: "methodname",
/* ... */
}
});
Your custom "email" validator is unnecessary; jQuery validate has its own. Here is an example of your password validator in action:
jQuery.validator.addMethod(
"myPasswordMethod",
function(value, element) {
// This is your regex, I have not looked closely at it to see if it is sensible
return value.match(/^[^\W][a-zA-Z0-9\_\-\.]+([a-zA-Z0-9\_\-\.]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/);
},
"Please enter a valid password"
);
$("#myForm").validate({
rules: {
pwd: "myPasswordMethod",
mail: "email" // don't reinvent the wheel; there is a built-in email validation method
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="myForm">
<label for="mail">Email</label>
<input id="mail" name="mail"><br>
<label for="pwd">Password</label>
<input id="pwd" name="pwd"><br>
</form>
As discussed exhaustively in comments, clientside password validation (or any other clientside validation) is insufficient on its own. Validate on the client for the user's convenience; re-validate on the server to prevent user shenanigans or to handle disabled clientside scripting.

Javascript mini validation script

I'm new to js. trying to create mini validation function which will check fields if they're empty or not.
What i wanna do is, to call func like that checkIfEmpty("fullname, email,..."), then inside function, check each field seperated by comma, collect empty fields to one array, and check at the end if this array is empty or not. Tried something like following func, but don't know all alternatives of php functions in js. Please help me to realize my idea..
function checkIfEmpty(fields)
{
var emptyFields=new Array();
fields=fields.split(',');
foreach(fields as field)
{
if (!field.val()) {
field.attr('class', 'invalid');
emptyFields[] = field;
}
}
if(emptyFields.length()==0){return true;}
else {return false;}
}
Seems like you want something like this:
$("input:text").each(function(i, field) {
if (!field.val()) {
field.addClass('invalid');
}
});
return ($("input.invald").length > 0); // return true if invalid fields
You could also set a class on each input that not suppose to be empty, then on form submission check each input that has this class.
$('#form_id').submit(function() {
$('.required').each(function() {
// if a input field that's required is empty
// we add the class '.invalid'
if(!$(this).val()) {
$(this).addClass('invalid');
}
});
// prevent the submission if number
// there is required fields still empty
return ($('input.invalid').length == 0);
});
This is an example form with one required field called email:
<form method="POST">
<input type="text" name="email" class="required" />
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="submit" value="SEND" />
</form>

Categories