avatar
build contact us form HTML

» First and foremost, you need to build Contact Us form based on HTML language as below:

<form id="contactform" name="contactform">
    <div class="row">
        <div class="col-md-12">
            <input name="name" id="name" type="text" placeholder="Name" />
        </div>
        <div class="col-md-6">
            <input name="email" id="email" type="email" placeholder="Email" />
        </div>
        <div class="col-md-6">
            <input name="subject" id="subject" type="text" placeholder="Subject" />
        </div>
        <div class="col-md-12">
            <textarea name="comments" id="comments" cols="40" rows="2" placeholder="Description"></textarea>
        </div>
    </div>
    <input type="submit" class="button" value="Submit" />
</form>

» After that, move to JavaScript and update logics for Contact Us form.

<script>
    const form = $('#contactform');
    const name = $('[name="name"]');
    const subject = $('[name="subject"]');
    const email = $('[name="email"]');
    const comments = $('[name="comments"]');

    jQuery.validator.addMethod("validateEmail", function (value) {
        if (/^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/.test(value)) {
            email.css({
                'border' : '1px solid transparent',
                'box-shadow': '0px 0px 0px 2px rgb(0 0 0 / 10%), 0px 1px 10px rgb(0 0 0 / 5%)'
            });
            return true;
        } else {
            email.css({
                'border' : '1px solid red',
                'box-shadow': 'none'
            });
            return false;
        }
    }, "Please enter a valid email address");

    jQuery.validator.addMethod("validateName", function (value) {
        if (/^[^]+$/.test(value)) {
            name.css({
                'border' : '1px solid transparent',
                'box-shadow': '0px 0px 0px 2px rgb(0 0 0 / 10%), 0px 1px 10px rgb(0 0 0 / 5%)'
            });
            return true;
        } else {
            name.css({
                'border' : '1px solid red',
                'box-shadow': 'none'
            });
            return false;
        }
    }, "Please fill in this field");

    jQuery.validator.addMethod("validateSub", function (value) {
        if (/^[^]+$/.test(value)) {
            subject.css({
                'border' : '1px solid transparent',
                'box-shadow': '0px 0px 0px 2px rgb(0 0 0 / 10%), 0px 1px 10px rgb(0 0 0 / 5%)'
            });
            return true;
        } else {
            subject.css({
                'border' : '1px solid red',
                'box-shadow': 'none'
            });
            return false;
        }
    }, "Please fill in this field");

    jQuery.validator.addMethod("validateMsg", function (value) {
        if (/^[^]+$/.test(value)) {
            comments.css({
                'border' : '1px solid transparent',
                'box-shadow': '0px 0px 0px 2px rgb(0 0 0 / 10%), 0px 1px 10px rgb(0 0 0 / 5%)'
            });
            return true;
        } else {
            comments.css({
                'border' : '1px solid red',
                'box-shadow': 'none'
            });
            return false;
        }
    }, "Please fill in this field");

    form.validate(
        {
            rules: {
                name: {
                    validateName: true
                },
                email: {
                    validateEmail: true
                },
                subject: {
                    validateSub: true
                },
                comments: {
                    validateMsg: true
                }
            }
        });

    form.on('submit', function (event) {
        if (!$(this).valid()) return;
        const formData = new FormData(this);
        event.preventDefault();
        $.ajax({
            url: '/api/contacts',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            method: 'POST',
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
            }
        }).done(function (data) {
            $('label.error').remove();
            if (0 === data.error.code) {
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000
                });
                Toast.fire({
                    type: 'success',
                    title: 'Thank you for contacting us!'
                })
                $('#name').val('');
                $('#email').val('');
                $('#subject').val('');
                $('#comments').val('');
            }
        }).fail(function (error) {
            let errors = $.parseJSON(error.responseText);
            $('label.error').remove();
            $.each(errors, function (key, value) {
                let el = $('#' + key);
                if(!el.next().is('label')) {
                    el.parent().append('<label class="error">'+value[0]+'</label>');
                }
            });
        });
    });
</script>

Note: if you use Laravel framework as backend layer and ContactUsController as below:

public function store(Request $request) {
    $request->merge([
        'created_at' => $this->freshTimestamp(),
        'updated_at' => $this->freshTimestamp()
    ]);
    $credentials = $request->only('name', 'email', 'subject');
    $rules = [
        'name' => 'required',
        'email' => 'regex:/^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/',
        'subject' => 'required',
    ];
    $customMessages = [
        'name.required' => Lang::get('strings.error.name'),
        'email.regex' => Lang::get('strings.error.email'),
        'subject.required' => Lang::get('strings.error.message')
    ];
    $validator = Validator::make($credentials, $rules, $customMessages);
    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);
    } else {
        $this->repository->create($request->all());
        return ([
            'error' => [
                'code' => 0,
                'message' => "Success"
            ]
        ]);
    }
}
24
DOM Javascript Open link JavaScript new tab disable click on html element add right tooltip in HTML Element
You need to login to do this manipulation!