I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}
Related
Requirement : To validate password and emailID entered by user.
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}
We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;
I have the following code which checks if a roll number is valid in the database selected by the postname variable. It was working in an earlier version where I hadn't introduced the second variable postname. But at the moment, this code is not working. What's the error here?
$(document).ready(function() { //function to check rollno is valid
$('#roll').keyup(function(event) {
var rolll=$('#roll').val();
var postname=$('#post').val();
$.get('CheckRollValidity',{roll:rolll},{post:postname},function(responseText) {
$('#status1').text(responseText);
});
});
});
Servlet
roll = request.getParameter("roll");
temp = request.getParameter("post");
table1 = "dbo."+post;
table2 = "dbo.user_candidates";
try
{
if (roll.length() < 10 || roll.length() > 10) {
result = "Please enter your " + len + "-digits roll number.";
count1 = 1;
}
else if (!roll.matches("[0-9]*"))
{
result = "Please enter digits only";
count1 = 1;
}
if (count1 == 0)
{
//database work
result="OK";
}
else
{
result = "Error";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(result);
Also, can I do the same via ajax, alternatively? Here I don't want the code working on pressing a submit button. Rather the working is happening on keypress.
You can't send two objects, you'll have to use one object with two values otherwise the second object is seen as the argument which should have been the callback
$.get('CheckRollValidity',{roll:rolll, post:postname},function(responseText) {
$('#status1').text(responseText);
});
I need to make a new method for jQuery Validator and don't know where to start.
I would like it check that the email entered includes: '#specificdomain.com'.
But that it is also the very last part of the input. For example #specificdomain.comChris would not do.
<script type="text/javascript">
jQuery.validator.addMethod("mustinclude", function(value, element) {
return this.optional(element) || value == ?
}, "must include #specificdomain.com at the end of the text input");
$(document).ready(function(){ .....
So far I've only come across value == value.match(), hence this is where I've got stuck.
Cheers Chris
jQuery.validator.addMethod('matchDomain', function(value, element) {
var s=value;
var split = s.split('#');
var regex = /^([a-zA-Z0-9_.+-])+$/;
var s2="#allcoles.com";
var optionalValue = this.optional(element);
if (optionalValue) {
return optionalValue;
}
if(regex.test(split[0]) && s2.equals(split[1]))
{
return true;
}
else
{
return false;
}
}, 'Please specify a #allcoles.com email');
The following worked for me:
jQuery.validator.addMethod('matchDomain', function(value, element) {
var s=value;
var split = s.split('#');
var regex = /^([a-zA-Z0-9_.+-])+$/;
**var s2="allcoles.com";** //The split array is the domain excluding the #
**var optionalValue = this.optional(element);** //This is how other methods in alternativeMethods.js Validator handle this.
**//Debugging - This is useful to see visually what is happening
//alert(split[0]); // Shows the inputted username i.e chris or smokey
//alert(split[1]); // Shows the inputted domain
//alert(regex.test(split[0])); //Shows unfilled inputs problem or bad characters, true if good, false if bad
//alert(s2 == split[1]);** // Shows if the inputted domain matches variable s2, if it does we get a true
if (optionalValue) {
return optionalValue;
}
**if(regex.test(split[0]) && (s2 == split[1]))** // has to be == not equals
{
return true;
}
else
{
return false;
}
}, 'Please specify a #allcoles.com email');
var s="abc#specificdomain.com"; OR var s=value;
var split = s.split('#');
var regex = /^([a-zA-Z0-9_.+-])/;
var s2="#specificdomain.com";
if(regex.test(split[0]) && s2 == split[1])
return true;
else
return false;
For example, I want to test a postcode is valid so I test the postcode using my regular expressions in a 'if else' scenario and call the function when the form is submitted.
function validatePostal(postalCode)
var re = new RegExp(/^([a-zA-Z]{2})([0-9]{1,2})[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var re2 = new RegExp(/^([cC]{1})([aA]{1})(2|18|17)[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var str = shipPostalCode.value;
if (re.test(str))
{
return true;
}
else if (re2.test(str))
{
return true;
alert("Congratulations!!");
}
else
{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
}
onclick="return (validatePostal(postalCode)"
How would i go about testing said postcode against another regular expression and then if the postcode is valid, only displaying a message to those in a particular area.
e.g. those who entered CA4 would get a message and those who entered DA4 would not?
Okay, so assuming that both re and re2 are the regular expressions for postcodes you want to accept, you could have a structure like:
if (re.test(str) || re2.test(str))
{
return true;
}
else
{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
Now if you want to do another check, like you said about "DA4" versus "CA4", you would have another regular expression for that (lets call it re3 to be consistent), and you could then have an inner if statement, like so:
if (re.test(str) || re2.test(str))
{
if (re3.test(str)) {
alert("You entered a CA4 postcode!");
} else {
alert("You did not enter a CA4 postcode :(.");
}
return true;
}
else
{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
function validatePostal(postalCode)
var re = new RegExp(/^([a-zA-Z]{2})([0-9]{1,2})[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var re2 = new RegExp(/^([cC]{1})([aA]{1})(2|18|17)[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var str = shipPostalCode.value;
var isPostalCodeValid = false;
if (re.test(str))
{
isPostalCodeValid = true;
}
else if (re2.test(str))
{
alert("Congratulations!!");
isPostalCodeValid = true;
}
if(isPostalCodeValid){
//Check for Postalcode and show mssg or not
}else{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
}
onclick="return (validatePostal(postalCode)"