i used to use jquery validation plugin but because of lack of this plugin with wysiwyg plugins i wrote a simple script to validate my form
i tried to do it like this
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article body</li>');
return false;
}
if ($('#ArticleTitle').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article title</li>');
return false;
}
$('#errors').hide();
return true ;
}
i found to 1 problem when it validate the form it's validating it field by field so the errors messages doesn't appear at once
i tried to do something like
var errors = [];
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
errors.push('<li>please enter your article body</li>');
var invalid = 1 ;
return false;
}
if ($('#ArticleTitle').val() == 0) {
errors.push('<li>please enter your article title</li>');
var invalid = 1 ;
return false;
}
if(invalid == 1){
$.each(errors , function(i, val) {
$('#errors').append(errors [i]);
});
}
$('#errors').hide();
return true ;
}
i tried to push errors as array elements and loop through them in case of invalid is true
bu this one doesn't work at it all ?
is there any way to make it work ?
if ($('#editor').val() == 0) // This is checking if value is 0
This does not make sense..
Try
if ($('#editor').val() == '') //Instead check for empty string
EDIT
Also you seem to be hiding the error's div in the end.
$('#errors').hide();
Try this code Instead
$('#validate').on('click', function() {
var errors = [];
var html = '<ul>' ;
valid = true;
$('#errors').empty();
if ($('#editor').val() == '') {
errors.push('<li>please enter your article body</li>');
valid = false;
}
if ($('#ArticleTitle').val() == '') {
errors.push('<li>please enter your article title</li>');
valid = false;
}
if (!valid) {
html += errors.join('') + '</ul>'
$('#errors').append(html);
}
else{
$('#errors').hide();
}
return valid;
});
DEMO
Related
I have following code to check if the inputs with the ids emailForm and nameForm are blank, this however isn't working when I test the form by leaving it blank.
function setInfo() {
if (document.getElementById("emailForm").value == null ||
document.getElementById("nameForm").value == null) {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Could someone help me with this, thanks!
Instead of checking for null specifically, you should check for falsy values. In some cases, the values for empty textboxes will be an empty string.
Replace this:
if (document.getElementById("emailForm").value == null || document.getElementById("nameForm").value == null) {
with this:
if (!document.getElementById("emailForm").value || !document.getElementById("nameForm").value) {
You shouldn't be checking whether the fields are null, you should be checking whether they content is an empty string (with .value == '').
This can be seen working in the following:
function setInfo() {
if (document.getElementById("emailForm").value == '' ||
document.getElementById("nameForm").value == '') {
console.log("Please fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
//loaded();
console.log("All sections filled in");
}
}
const button = document.getElementById('go');
button.addEventListener('click', function() {
setInfo();
});
<input id="emailForm" />
<input id="nameForm" />
<button id="go">Go</button>
Make sure you calling function setInfo()
function setInfo() {
// You can check Value.Length also or
if (document.getElementById("emailForm").value === "" ||
document.getElementById("nameForm").value === "") {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Try below solution:
function setInfo() {
var email=document.getElementById("emailForm").value;
var name=document.getElementById("nameForm").value;
if (email=='' || email==null || name=='' || name== null ) { // OR if (!email || !name)
alert("Please Fill in all sections");
return;
} else {
loaded();
}
}
You should check whether the string is empty or not instead of null. Try using the code below:
function setInfo() {
var a=document.getElementById("emailForm").value;
var b=document.getElementById("nameForm").value;
if (a == "" ||
b == "") {
alert("Please Fill in all sections");
} else {
email =
document.getElementById("emailForm").value;
name =
document.getElementById("nameForm").value;
alert("success alert");
}
}
I have a form using Tinymce, I need to check if it only contains space.
I try using this function
function validation_form()
{
var content = tinyMCE.get('main-comment').getContent().replace(' ','');
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
But it returns true when I input several spaces and submit, I want it to return false instead.
Can anyone help me?
Thanks,
use $.trim ,
it is clean and readable.
function validation_form()
{
var content = $.trim(tinyMCE.get('main-comment').getContent({format: 'text'}));
if(content.length == 0) {
return false;
}
return true;
}
Updated: format as text, to get text content from editor. check fiddle
-- Originally wrote it in PHP --
function validation_form()
{
var content = $.trim(tinyMCE.get('main-comment').getContent());
if(content.length == 0) {
return false;
}
return true;
}
Is Correct #A.T
You can use javascript's trim method.
function validation_form()
{
var content = tinyMCE.get('main-comment').getContent().replace(' ','').trim();
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
For more information, please check here
Solution for the same while using Angular Reactive Form Validation
Give this custom validator function in typescript file
emptyLinesValiadtor(control:FormControl):{[s:string]:boolean} | null {
let content = control.value.replaceAll(/ /gm,'')
.trim().split(" ").join("").replaceAll('<p></p>','').trim();
if(content == "" || content == null) {
return {'emptyLines': true}
}
return null;
}
In your Reactive form builder/declaration
this.formName= this.formBuilder.group({
textArea:['',this.emptyLinesValiadtor]
});
In your template form
<div
*ngIf="sForm.submitted && f.textArea.errors">
<div *ngIf="f.textArea.errors.emptyLines">
<div>Answer cannot contain empty lines/spaces</div>
</div>
</div>
where sform is reference variable and f is a typescript get method like below
get f() {
return this.formName.controls;
}
Can someone help me out with validation of two text-box with same email Id.
I was able to pop an alert if both the text-box contain the same email Id via JavaScript(my requirement was both text-box cant have same email) but now I m facing a problem if second text box contain more then one email_Id separated my comma(,) the validation doesn't work.
I don't want email that is present in first text box repeat into second text-box.
My code:
<script language="javascript" type="text/javascript">
function validated() {
if (document.getElementById("<%=txtCountry.ClientID %>").value = document.getElementById("<%=txtnewViewer.ClientID %>").value) {
alert("Presenter cant be attende");
return false;
}Else{
return true;
}
}
</script>
check this code out
<script language="javascript" type="text/javascript">
function validated()
{
if (document.getElementById("<%=textbox1.id %>").value == document.getElementById("<%=textbox2.id %>").value)
{
alert("text-box cant have same email");
return false;
}
else
{
alert("Valid");
return true;
}
}
</script>
Can you try this.
var f_email = document.getElementById("f_email").value;
var s_email= document.getElementById("s_email").value;
if(f_email === s_email) {
// do something when email ids are same.
alert("email ids are same");
}
else {
// do something when email ids are same.
alert("email ids are not same");
}
First, you if statement contains an = who always return true and modify your variable (in place of ==).
function validated() {
var clientId = document.getElementById("<%=txtCountry.ClientID %>").value,
viewerId = document.getElementById("<%=txtnewViewer.ClientID %>").value;
if (clientId == viewerId) {
alert("Presenter cant be attende");
return false;
}
return true;
}
After that you can use : Array.indexOf():
var clients = clientId.split(","), viewers = viewerId.split(",");
// Here we have two arrays with all datas
for(var i = 0; i < clients.length; i++){
var k = viewers.indexOf(clients[i]);
if(k !== -1) {
alert(clients[i], "=", viewers[k]);
}
}
Hi I have designed my form now i am unsure how to combine all the alert messages instead of them popping up one at a time , please could someone tell my how to do this in simple terms as i am new to javascript. thankyou in advance. below is my script.
function validateForm() {
// this part of the script will collate all errors into one should the user leave an input blank
var Fname=document.forms["myForm"]["fname"].value;
var Lname=document.forms["myForm"]["lname"].value;
var address=document.forms["myForm"]["addr1"].value;
var postcode=document.forms["myForm"]["pcode"].value;
var email=document.forms["myForm"]["email"].value;
var number=document.forms["myForm"]["tel"].value;
var date=document.forms["myForm"]["mydate"].value;
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date)
{
alert("Please make sure all fields are filled or checked correctly out ");
return false;
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode))
{
alert("That Post Code is incorrect, correct way mk4 4tr");
return false;
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail))
{
alert("That email is incorrect");
return false;
}
// end of email script
// start of phone number script
var phonestring = /^(?:0|\+44)[12378]\d{8,9}$/;
if (!number.match(phonestring))
{
alert(" incorrect,correct format 01908234874");
return false;
}
// end of phone script
//start of gender script
if ( ( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
// end of gender script
//start of age group script
if((myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )){
alert("please select an age group");
return false;
}
// end of age script
//start of datefield
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/;
if (!date.match(dateformat))
{
alert("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016");
return false;
}
var today = new Date();
var courseYear =date.substr(6,4) // use substr or substring to capture the last four digits
var courseMonth =date.substr(3,2) // use substr or substring to capture the four and fifth digits
var courseDay = date.substr(0,2)//e the first and second digits
var dateToCompare = new Date(courseYear, courseMonth, courseDay);
if (dateToCompare < today) {
alert("this date is in the past");
return false; }
//end of date field
else
{ alert(" Thank you a member of our team will get back to you shortly");
return true;}
}
create some kind of collection that you can append to and instead of alerting independantly, just add them to the set. Something like:
function validateForm(){
var errors = []; // new array to hold all the errors
/*
validation code that instead of
alert('error')
use
errors.push('error');
Also remove any premature `return` statements and
leave them until the end.
*/
// next check if there are errors
if (errors.length > 0){
// display them
alert('Following errors found:\n- ' + errors.join('\n- '));
// also return false to flag there was a problem
return false;
}
// if we reached this code there were no errors
return true;
}
Add all your errors to an array and then alert them at the end, if any exist:
function validateForm() {
var errors = []; //array for holding errors
.
.
.
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date) {
errors.push("Please make sure all fields are filled or checked correctly out "); //add error
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode)) {
errors.push("That Post Code is incorrect, correct way mk4 4tr"); //add error
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail)) {
errors.push("That email is incorrect"); //add error
}
if(errors.length > 0) {
alert('The following errors occurred: ' + errors.join('\n')); //alert errors if they exist
return false;
}
return true; // allow submit
}
I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/