JSFiddle - React, Tailwind, and code Playground
HTML
<form id="registrationForm" method="post" action="process.jsp"
onsubmit="return validate(this)">
<p class="form">
*Username<br />
<input type="text"
id="txtLogin" name="login" maxlength="32"
title="Username" required="true" />
</p>
<p class="form">
*Password<br />
<input type="password"
id="pwdPassword" name="password"
title="Password" required="true"
minlength="8" maxlength="16" />
</p>
<p class="form">
*Confirm<br />
<input type="password"
id="pwdConfirm" name="confirm"
title="Confirm" required="true"
confirm="pwdPassword" />
</p>
<p class="form">
*First Name<br />
<input type="text"
id="txtFirstName" name="first_name" maxlength="255"
title="First Name" required="true" />
</p>
<p class="form">
*Last Name<br />
<input type="text"
id="txtLastName" name="last_name" maxlength="255"
title="Last Name" required="true" />
</p>
<p class="form">
*Email Address<br />
<input type="text"
id="txtEmail" name="email" maxlength="255"
title="Email Address" required="true" />
</p>
<p class="form">
*User Type<br />
<select
id="cboUserTypeId" name="user_type_id"
title="User Type" required="true">
<option></option>
<option value="1">Administrator</option>
<option value="2">Member</option>
</select>
</p>
<button type="submit">Save</button>
</form>
JavaScript
function validate(form) {
var elements = form.getElementsByTagName('*');
var input = null;
var ok = true;
// Search for invalid inputs
for (var i = 0; i < elements.length; i++) {
input = elements[i];
minLength = (input.minlength) ? input.minlength : 0;
if (input.required == 'true') {
if (input.tagName.toLowerCase() == 'select') {
if (input.options.length == 0 ||
!input[input.selectedIndex].value) {
ok = false;
}
} else if (!input.value || input.value.length < minLength) {
ok = false;
}
if (!ok) {
window.alert('Please complete field "' + input.title + '"');
try {
input.focus();
} catch (e) {
}
return false;
}
}
if (input.confirm && input.confirm != '') {
if (input.value != document.getElementById(input.confirm).value) {
window.alert(document.getElementById(input.confirm).title
+ ' and ' + input.title + ' do not match.');
return false;
}
}
}
return true;
}
// Focuses on the first <input> or <select> field in the specified form
function focusForm(formId) {
var elements = (formId)
? document.getElementById(formId).getElementsByTagName('*')
: document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
input = elements[i];
if (input.tagName.toLowerCase() == 'input' ||
input.tagName.toLowerCase() == 'select') {
input.focus();
break;
}
}
return true;
}