In a Svelte app, I have a form with simple validation.
The form
<form id="surveyForm" class="mt-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="First name">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Last name">
</div>
<button class="btn btn-full" on:click={Continue}>Continue</button>
</form>
The validation:
import {fly, fade} from 'svelte/transition';
let hasError = false;
let errMessage = "";
let isSuccessVisible = false;
function validateInput() {
var surveyForm = document.getElementById('surveyForm'),
inputFields = surveyForm.querySelectorAll('input[type=text]');
hasError = false;
inputFields.forEach(function(field) {
field.classList.remove("is-invalid");
var inputFieldVal = field.value;
if (inputFieldVal.length == 0) {
field.classList.add("is-invalid");
hasError = true;
}
});
errMessage = "All the fileds are mandatory";
}
function Continue(e) {
e.preventDefault();
validateInput();
if (hasError == false) {
isSuccessVisible = true;
setTimeout(function() {
isSuccessVisible = false;
}, 3000);
}
}
In order to give invalid form fields a red border, I use border: 1px solid #c00 !important:
.error-alert {
border: 1px solid #c00 !important;
color: #c00;
}
The class is-invalid is correctly added (and removed), yet, the default global.css styles overwrite my component-level styles, as you can see in this REPL.
Why does this happen? What is a reliable fix?
NOTE: The case described is a simplified one, in reality I might need other validations, like making sure the value is numeric. The solution I have to implement is not a very specific one.