Reputation: 41
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.
Upvotes: 2
Views: 24
Reputation: 388396
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;
}
Upvotes: 1