-3

I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.

I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.

Andrio
  • 1,852
  • 2
  • 25
  • 54
  • 2
    Please post your code. – CertainPerformance Aug 19 '18 at 01:00
  • Why don't you want to use a `
    ` element? It would give you access to html validation and all the wonderful CSS styling that comes with it :)
    – stwilz Aug 19 '18 at 01:10
  • @stwilz I suppose I can, I guess I'm not using `
    ` because I don't actually want to use the form's submit action
    – Andrio Aug 19 '18 at 01:12
  • 1
    Please have a look [here](https://stackoverflow.com/help/how-to-ask) and please "Search, and research", googling "form validation javascript" gives you a lot of results including posts on SO – luke-codewalker Aug 19 '18 at 01:28
  • Possible duplicate of [JavaScript validation for empty input field](https://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field) – luke-codewalker Aug 19 '18 at 01:38

5 Answers5

2

I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.

Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.

//This function will trim extra whitespaces form input.
function trimInput(element){
    $(element).val($(element).val().replace(/\s+/g, " ").trim());
}

//This function will check if the name is empty
function isEmpty(s){
 var valid = /\S+/.test(s);
 return valid;
}

//This function will validate name.
function isName(name){
 var valid = /^[a-zA-Z]*$/.test(name);
 return valid;
}
  
$('#myForm').submit(function(e){
 e.preventDefault();
  var fname = $(this).find('input[name="fname"]');
  var lname = $(this).find('input[name="lname"]');
  var flag = true;
  trimInput(fname);
  trimInput(lname);
  if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
   alert("First name is invalid.");
    flag = false;
  }
  if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
   alert("Last name is invalid.");
    flag = false;
  }
  if(flag){
   alert("Everything is Okay");
   //Code to POST form data goes here... 
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
  <input type="text" name="fname" placeholder="Firstname">
  <input type="text" name="lname" placeholder="Last Name">
  <input type="submit" name="submit" value="Submit">
</form>

I am not using the <form> tag for this.

Then the code will be like

//This function will trim extra whitespaces form input.
function trimInput(element) {
  $(element).val($(element).val().replace(/\s+/g, " ").trim());
}

//This function will check if the name is empty
function isEmpty(s) {
  var valid = /\S+/.test(s);
  return valid;
}

//This function will validate name.
function isName(name) {
  var valid = /^[a-zA-Z]*$/.test(name);
  return valid;
}

$('#submit').click(function() {
  var fname = $('#fname');
  var lname = $('#lname');
  var flag = true;
  trimInput(fname);
  trimInput(lname);
  if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
    alert("First name is invalid.");
    flag = false;
  }
  if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
    alert("Last name is invalid.");
    flag = false;
  }
  if (flag) {
    alert("Everything is Okay");
    //Code to POST form data goes here... 
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>

Check the code on jsFiddle. Hope this will be helpful.

Anshuman
  • 758
  • 7
  • 23
1

Here is an example which may help you:

$('#save').click(function() {
  var errors = [];
  var name = $('#name').val();
  var vorname = $('#vorname').val();

  if (!name) {
    errors.push("Name can't be left blank");
  }
  if (!vorname) {
    errors.push("Vorname can't be left blank");
  }
  if (errors.length == 0) {
      console.log('Ajax started');
    //put here your ajax function
  } else {
    for (var i in errors) {
      console.log(errors[i]);
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
ferhado
  • 2,363
  • 2
  • 12
  • 35
1

here is an example using the popular add on jquery validate. https://jqueryvalidation.org/ click the run snippet button below

$(document).ready(function() {
  $("#form").validate({
    rules: {
      "firstname": {
        required: true,
      },
      "lastname": {
        required: true,
      }
    },
    messages: {
      "firstname": {
        required: "Please, enter a first name"
      },
      "lastname": {
        required: "Please, enter a last name"
      },
    },
    submitHandler: function(form) { // for demo
      alert('valid form submitted'); // for demo
      return false; // for demo
    }
  });

});
body {
  padding: 20px;
}

label {
  display: block;
}

input.error {
  border: 1px solid red;
}

label.error {
  font-weight: normal;
  color: red;
}

button {
  display: block;
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>

<form id="form" method="post" action="#">
  <label for="firstname">First Name</label>
  <input type="text" name="firstname" id="firstname" />
  <label for="lastname">Last Name</label>
  <input type="text" name="lastname" id="lastname" />
  <button type="submit">Submit</button>
</form>
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79
1

Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.

Given the following HTML:

<form>
  <input type="text" class="text1">
  <input type="text" class="text2">
  <button type="button">Send</button>
</form>

You could use this for the jQuery part:

$('button').click(function() {
    var txt1 = $(this).siblings('.text1').val();
    var txt2 = $(this).siblings('.text2').val();
    if (txt1.length && txt2.length) {
      // do your ajaxy stuff here
    } else {
      alert("Imput some friggin' text!");
    }
});

$(this) selects the button clicked. .siblings('.text1') selects the input with class text1 inside the same block as the clicked button.

https://jsfiddle.net/sg1x0c3q/7/

Martin Geldart
  • 407
  • 2
  • 8
  • What if the `txt1` and `txt2` have invalid characters like `/ , ?..` etc. – Anshuman Aug 19 '18 at 04:10
  • 1
    @iNullPointer: OP asked 'so they can't be left blank'. That is what I checked for. You down-voted for that?!! Jeez – Martin Geldart Aug 19 '18 at 11:38
  • What is your point @iNullPointer? He's checking if they are empty as per the instructions he was given. If OP wants to check that the input is valid, then OP should have asked for that. – TheCarver Aug 19 '18 at 11:41
1

As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)

// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
  return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
  ...collection,
  [textarea.name]: textarea.value
  }), {})
}

// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
  return Object.values(obj).length == Object.values(obj).filter(value => value).length
}

// If all key value pairs are not falsy then submit
window.submit = () => {
  const payload = createPayload()
  if (objectHasAllValues(payload)) {
    fetch('/your/api', payload)
  }
}

This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.

This scales and doesn't need jQuery :)

Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/

stwilz
  • 2,226
  • 2
  • 21
  • 24
  • And I wouldn't recommend writing functions to the window like I have in this example ie `window.submit`. It's just written like as a proof of concept. – stwilz Aug 19 '18 at 01:39
  • 1
    Note; there's a lot of features in this code that are not yet fully supported by browsers. Both `fetch()` and arrow functions won't work in any version of IE. If you need this support, use a transpiler like Babel or find the relevant polyfills. – Martin Geldart Aug 19 '18 at 01:45
  • Correct @MartinGeldart! But don't be afraid to use new features in JS @Andrio. If your not already using babel or typescript be sure to find a good boilerplate to start your project from. – stwilz Aug 19 '18 at 01:53