1

For instance in this example;

<form>
    <input type="email" name="email" id="useremail" placeholder="Email Address" required> <br>
    <input type="tel" name="phone" id="userphone" placeholder="Phone Number" maxlength="10" required> <br>
    <input type="submit" id="sidebarformsubmit" value="Submit">
</form>

Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".

Reword: Can at least one of the form inputs be mandatory, both is allowed as is one or the other but not none. In the above example, the user needs to have at least one form of communication whether that be phone number or email. They can have both however, but not none.

If so, how would you go about this?

homer5677
  • 585
  • 1
  • 6
  • 11
  • Validate in JavaScript on form submit. If at least one field is non-empty - return `true` and the form will submit. Otherwise return `false` and the submission will be canceled – Yuriy Galanter May 17 '14 at 00:40
  • you can make use of **or** || operator – mrdeveloper May 17 '14 at 00:42
  • You are using HTML5 validation. Either this, or jQuery. For custom validaition, as you described, I would go with jQuery. Change `email` and `tel` types to `text` and find a way to validate your fields e.g. with regular expressions. – lesssugar May 17 '14 at 00:43

2 Answers2

2

You can easily capture the change events from the inputs and set the required attribute accordingly. Like this:

var email = document.getElementById('useremail'),
    phone = document.getElementById('userphone');
function onchange(){
    email[phone.value?'removeAttribute':'setAttribute']('required','required');
    phone[email.value?'removeAttribute':'setAttribute']('required','required');
}
email.addEventListener('change',onchange);
phone.addEventListener('change',onchange);

jsfiddle

A1rPun
  • 16,287
  • 7
  • 57
  • 90
0

Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".

1) No. If you use HTML5 required on a field then that field is required. There is no way to specify interdependence.

2) Yes. You can use client-side javascript validation, generally hooked to a form submit event to do as-complex-as-you-like validation. Prevent the submit by returning false from the event handler if you don't pass validation.

3) Yes. You can do validation that can be as complex as necessary on the server when you have received the submitted form, and return directly to the form if something is wrong.

3b) You Must do validation on the server, even if you have great client-side javascript validation, otherwise I will buy things from your site for one penny. You must not trust the client.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Stephen P
  • 14,422
  • 2
  • 43
  • 67