Validation not works on all fields - javascript

I am working on a basic web application and i want to validate some fields of it and there is some field which is not mandtory but if it is there then in should be valid like url.
so for that my code is
validate:function(attrs){
var obTobeValidate={};
var regexp = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g;
obTobeValidate.questionImageUrl=$("#addSolvedExampleContainer .solvedQuestionImage").val();
obTobeValidate.solutionImageUrl=$("#addSolvedExampleContainer .solvedQuestionSolutionImage").val();
obTobeValidate.videoUrl=$("#addSolvedExampleContainer .solvedQuestionVideoUrl").val();
if(!attrs.title){
alert("please mention title..");
return false;
}
if(!attrs.question){
alert("please enter the question");
return false;
}
if(!attrs.solution){
alert("please enter the solution for the question..");
return false;
}
if (obTobeValidate.questionImageUrl="" || obTobeValidate.questionImageUrl.match(regexp))
{
return true;
}
else{
alert("please enter valid url of Question");
return false;
}
if (obTobeValidate.solutionImageUrl="" || obTobeValidate.solutionImageUrl.match(regexp))
{
return true;
}
else{
alert("please enter valid url for Solution..");
return false;
}
if (obTobeValidate.videoUrl="" || obTobeValidate.videoUrl.match(regexp))
{
return true;
}
else{
alert("please enter valid url for Video..");
return false;
}
return true;
},
and after executing this code if i left the questionImageUrl blank it shows please enter valid url and url validation is not worked in other fields like videoUrl etc.
please help me out.

If the if statement you are using assignment operator(=) instead of comparator(==).
Also if the condition is valid, don't return because you need to check other fields so
validate: function (attrs) {
var obTobeValidate = {};
var regexp = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g;
obTobeValidate.questionImageUrl = $("#addSolvedExampleContainer .solvedQuestionImage").val();
obTobeValidate.solutionImageUrl = $("#addSolvedExampleContainer .solvedQuestionSolutionImage").val();
obTobeValidate.videoUrl = $("#addSolvedExampleContainer .solvedQuestionVideoUrl").val();
if (!attrs.title) {
alert("please mention title..");
return false;
}
if (!attrs.question) {
alert("please enter the question");
return false;
}
if (!attrs.solution) {
alert("please enter the solution for the question..");
return false;
}
if (obTobeValidate.questionImageUrl != "" && !obTobeValidate.questionImageUrl.match(regexp)) {
return false;
}
if (obTobeValidate.solutionImageUrl != "" && !obTobeValidate.solutionImageUrl.match(regexp)) {
alert("please enter valid url for Solution..");
return false;
}
if (obTobeValidate.videoUrl != "" && !obTobeValidate.videoUrl.match(regexp)) {
alert("please enter valid url for Video..");
return false;
}
return true;
}

Related

validation form : how to show error message all at one time for the blank input instead of one by one?

I want to validate my form, if any of the input field is blank, the error warning will show beside the blank input field. The error message must be comes out all at one time for the blank input, not show one by one. How to do this?
Below is my javascript code :
function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}
var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}
var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}
var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}
var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}
}
You should start your function with var ok = true, and in each if-block, instead of having return false, you should set ok = false. At the end, return ok.
Here's what that might look like:
function doValidate() {
var ok = true;
var form = document.forms.form;
var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}
var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}
var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}
var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}
var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}
return ok;
}
(I've taken the liberty of changing to a more consistent formatting style, improving some variable-names, simplifying some access patterns, and replacing an alert with an inline error message like the others.)

How do I correctly perform form validation in JavaScript?

I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}

Javascript: Validation alerts 2

My goal is this:
Check if email and name are empty. If so, give 'Enter email or name' alert.
If they do, check for an # in email If none is found, give 'Bad email' alert.
Check if email and name contain any letters, if they do, give 'Success' alert
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");}
return false;
if(email.indexOf("#") == -1){
alert("Bad email");}
return false;
var a = email.length;
var b = name.length;
if(a==>0, b==>0){
alert("Message sent");}
return true;
}
This is what I've come up with so far, but it isn't working. I'm quite new at javascript so maybe you guys could tell me what I've done wrong?
The problem you're having is the close bracket is in the wrong place. You have it at the end of your alert statement and you probably want the return to be included with your if statement. if this is the case then change it to be:
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");
return false;
}
if(email.indexOf("#") == -1){
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if(a > 0 && b > 0){
alert("Message sent");
return true;
}
}
A better way to do the same thing would be because that way you're not checking the variables for length and size twice:
function test(email, name) {
var a = email.length;
var b = name.length;
if ( a > 0 && b > 0 ) {
// ignore 0 because email addresses shouldn't start with #
if ( email.indexOf("#") > 0 ) {
alert("Message sent");
return true;
}
else {
alert("Bad email");
return false;
}
}
else {
alert("Enter mail or name");
return false;
}
}
Try this JSFiddle that seems to fit your needs http://jsfiddle.net/9nF5W/
function test(email, name) {
if (email == "" || name == "") {
alert("Enter mail or name");
return false;
}
if (email.indexOf("#") == -1) {
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if (a > 0 && b > 0) {
alert("Message sent");
}
return true;
}
test('tes#t', 'test');
I think there is an other mistake than the returns statements in "if(a==>0, b==>0){" by the way.

Validation for string

I want to validate a username using Javascript. I have validated if media name is null. Now I want to check special characters are not taken except space.
<input type="text" name="medianame" id="medianame" value="" required="required">
<a class="edit" href="" id="edit" onclick="return chk_val()">Save</a>
<script>
function chk_val() {
if (document.getElementById('medianame').value == "") {
alert("Please enter name");
return false;
}
else {
return false;
}
}
</script>
You can use a regular expression to test whether a string contains only the characters you want to allow:
/^[a-z ]+$/i
...or test for characters that aren't allowed:
/[^a-z ]/i
Use the .test() method in your function as follows:
function chk_val() {
var val = document.getElementById('medianame').value;
if (val === "") {
alert("Please enter name");
return false;
} else if (/[^a-z ]/i.test(val)) {
alert("Please enter only letters or spaces");
return false;
}
return true;
}
function chk_val()
{
var error = false;
var name = document.getElementById('medianame').value;
if (name == "")
error = true;
else if( /^[A-z ]+$/.test(name) == false)
error = true;
if(error)
{
alert("Please enter correct name");
return false;
}
return true;
}
This will check for all the expressions possible. You can filter your needs from this.
var yourExp = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g;
Then you can match like
var yourStr = document.getElementById('medianame').value;
if( yourStr.match(yourExp) == True ){
alert('Matched');
}

Form validation fails but form gets submitted

I am having trouble validation a form and staying on the same page. Below is my javascript validation which is working as i get popups.
function valueChecks(input){
var reqdFields = false;
var ncFields = false;
var catCheck = false;
var refCheck = false;
var dtCheck = false;
var retval = false;
reqdFields = checkRequiredFields(input) ;
ncFields = checkNonComplianceFields(input);
catCheck = checkCat();
refCheck = checkRef();
dtCheck = subDate();
var mesgNo="0";
if (reqdFields == true){
mesgNo="0";
} else { mesgNo="1";
}
if (catCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"2";
}
if (refCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"3";
}
if (dtCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"4";
}
if (ncFields == true){
mesgNo=mesgNo+"0";
} else {mesgNo=mesgNo+"5";
}
if (mesgNo =="00000"){
retval=true;
}
else if ((mesgNo =="10000")||(mesgNo =="12000")||(mesgNo =="12300")||(mesgNo =="12340")||(mesgNo =="12345")||(mesgNo =="10300")||(mesgNo =="10340")||(mesgNo =="10040")){
retval = false;
alert("Please check that you have filled in all the Mandatory Fields");
}
else if ((mesgNo =="02000")||(mesgNo =="02300")||(mesgNo =="02040")||(mesgNo =="02340")||(mesgNo =="02345")){
retval = false;
}
else if ((mesgNo =="00300")||(mesgNo =="00340")||(mesgNo =="00345")){
retval = false;
alert ("Please enter at least one Reference Value (File Number, STT or BL Number)");
}
else if ((mesgNo =="0004")||(mesgNo =="00045")){
retval = false;
alert ("The Incident Date must be less than or equal today's Date");
}
else if ((mesgNo =="0005")){
retval = false;
alert ("Please enter at least one Non Conforming Party");
}
return retval;
}
And this is how i declare my form.
<html:form action="/qaeditsrl" onsubmit="return valueChecks(this);" >
<input type=submit value="Submit" name="method" >
Can someone tell me why this is going wrong?
Try changing the submit button to input type=button.
Remove the onsubmit on the form, and add an id.
Then add onclick on the button doing all the checks,
if no errors were found use document.getElementById('formId').submit() for submitting;

Categories